package org.dtrd.modules.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.util.*;
import org.dtrd.config.common.PathUtil;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.SystemState;
import org.dtrd.config.system.SystemState.ResponseState;
import org.dtrd.config.wechat.WechatMobile;
import org.dtrd.config.wechat.WechatMobileManual;
import org.dtrd.config.wechat.api.impl.WechatApi;
import org.dtrd.config.wechat.config.WechatConstant;
import org.dtrd.config.wechat.config.WechatConstant.MiniprogramVersion;
import org.dtrd.config.wechat.config.WechatConstant.WechatMiniprogram;
import org.dtrd.config.wechat.config.WechatUtil;
import org.dtrd.config.wechat.entity.bean.*;
import org.dtrd.config.wechat.entity.bean.miniprogram.LineColor;
import org.dtrd.config.wechat.entity.bean.officialaccount.WechatOfficialAccountUserInfo;
import org.dtrd.config.wechat.entity.request.WechatSignatureRequest;
import org.dtrd.config.wechat.entity.request.officialaccount.WxBindingTagRequest;
import org.dtrd.config.wechat.entity.request.officialaccount.WxOfficialAccountsLoginRequest;
import org.dtrd.config.wechat.entity.request.miniprogram.WxMiniprogramLoginRequest;
import org.dtrd.config.wechat.entity.response.WechatResponse;
import org.dtrd.config.wechat.entity.response.WxTagListResponse;
import org.dtrd.modules.doctor.entity.po.DtrdEntRdDoctor;
import org.dtrd.modules.doctor.service.IDtrdEntRdDoctorService;
import org.dtrd.modules.patient.entity.po.DtrdEntRdPatient;
import org.dtrd.modules.patient.service.IDtrdEntRdPatientService;
import org.dtrd.modules.system.entity.bean.qiyeweixin.OfficialAccountLoginResponse;
import org.dtrd.modules.system.entity.bean.weixin.WxEventPushBean;
import org.dtrd.modules.system.entity.bean.weixin.WxPassiveResp;
import org.dtrd.modules.system.entity.request.CreateTagRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author 萧
 * @date:2021-09-26 12:58 下午
 **/
@RestController
@RequestMapping("/sys/wechat")
@Slf4j
@ApiSort(12)
@Api(tags = "微信公众号、小程序接口")
public class WechatController extends BaseController {

    @Lazy
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private WechatApi wechatApi;
    @Autowired
    private IDtrdEntRdPatientService patientService;
    @Autowired
    private IDtrdEntRdDoctorService doctorService;

    @Value("${dtrd.wechat.tools.app_id}")
    private String toolsAppId;

    @Value("${dtrd.wechat.tools.appsecret}")
    private String toolsAppSecret;

    /**
     * 微信登录校验反馈成功码
     */
    private static final int SUCCESS_CODE = 0;

    //region================================  小程序相关接口 开始  ================================

    @ApiOperation("获取小程序AccessToken")
    @PostMapping("/getAccessToken")
    public Result<?> getAccessToken(@RequestBody WxMiniprogramLoginRequest request) {
        // 小程序类型
        Integer type = ObjectWrapperUtil.wrapper(request, WechatMiniprogram.HEALTHY.getType(), WxMiniprogramLoginRequest::getType);
        String appId = null, appsecret = null;
        if (type == WechatMiniprogram.HEALTHY.getType()) {
            appId = WechatUtil.getClientId();
            appsecret = WechatUtil.getAccessKeySecret();
        } else if (type == WechatMiniprogram.TOOLS.getType()) {
            appId = toolsAppId;
            appsecret = toolsAppSecret;
        }
        if (appId == null) {
            return error(ResponseState.STATE_PARAMS_ERROR);
        }
        AccessToken accessToken = wechatApi.getAccessToken(appId, appsecret);
        return Result.OK(accessToken);
    }

    @ApiOperation("登录凭证校验")
    @PostMapping("/login")
    public Result<?> login(@RequestBody @Validated WxMiniprogramLoginRequest request) {
        log.info("WechatController.login.[request] request = " + request);
        // 小程序类型
        Integer type = ObjectWrapperUtil.wrapper(request, WechatMiniprogram.HEALTHY.getType(), WxMiniprogramLoginRequest::getType);
        String appId = null, appsecret = null;
        if (type == WechatMiniprogram.HEALTHY.getType()) {
            appId = WechatUtil.getClientId();
            appsecret = WechatUtil.getAccessKeySecret();
        } else if (type == WechatMiniprogram.TOOLS.getType()) {
            appId = toolsAppId;
            appsecret = toolsAppSecret;
        }
        log.info("WechatController.login.[request] type="+type+"; ");
        if (appId == null) {
            return error(ResponseState.STATE_PARAMS_ERROR);
        }
        Object openIdObj = redisUtil.get(request.getJsCode());
        String openid;
        String unionid = null;
        if (openIdObj == null) {
            JSONObject obj = wechatApi.code2Session(appId, appsecret, request.getJsCode());
            if (obj == null) {
                return error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
            } else {
                log.info("WechatController.login.[request]  obj = " + obj);
                int errorCode = obj.getIntValue("errcode");
                if (errorCode == SUCCESS_CODE) {
                    // 设置5分钟有效
                    openid = obj.getString("openid");
                    unionid = obj.getString("unionid");
                    if (openid == null || unionid == null) {
                        return error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
                    }
                    redisUtil.set(openid, obj.getString("session_key"));
                } else {
                    return Result.error(errorCode, obj.getString("errmsg"));
                }
            }
        } else {
            openid = StrUtil.str(openIdObj, StandardCharsets.UTF_8);
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("openId", openid);
        map.put("unionId", unionid);
        DtrdEntRdPatient patientInfo=null;
        if (type == WechatMiniprogram.HEALTHY.getType()) {
            patientInfo = patientService.getPatientInfoByUnionId(unionid);
            if (patientInfo == null) {
                patientInfo = patientService.createPatientByOpenIdAndUnionid(openid, unionid);
            }
            // 回填unionid 和 openid
            if (patientInfo.getWxUnionid() == null || patientInfo.getWxOpenid() == null) {
                patientService.updatePatientUnionIdAndWxOpenid(patientInfo.getDataId(), unionid, openid);
            }

        } else if (type == WechatMiniprogram.TOOLS.getType()) {
            patientInfo = patientService.getPatientInfoByUnionId(unionid);
            if (patientInfo == null) {
                patientInfo = patientService.createRecordByToolsId(openid, unionid);
            }
            // 回填unionid 和 openid
            if (patientInfo.getWxUnionid() == null || patientInfo.getWxToolsOpenid() == null) {
                patientService.updatePatientToolsInfo(patientInfo.getDataId(), unionid, openid);
            }
        }

        map.put("userId", patientInfo.getDataId());
        map.put("avatar", patientInfo.getPatientsImg());
        map.put("name", patientInfo.getPatientsName());
        log.info("小程序登陆用户: id={},name={} ", patientInfo.getDataId(), patientInfo.getPatientsName());
        return Result.OK(map);
    }

    @ApiOperation("数据解密")
    @PostMapping("/authEncrypted")
    public Result<?> authEncrypted(@RequestBody WechatEncryptInfo data) {
        if (StrUtil.isEmpty(data.getOpenId())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        Object sessionKey = redisUtil.get(data.getOpenId());
        if (sessionKey == null) {
            return error(SystemState.ResponseState.STATE_PARAMS_ERROR);
        }
        JSONObject result = wechatApi.decryptInfo(StrUtil.str(sessionKey, StandardCharsets.UTF_8), data.getEncryptedData(), data.getRawData(), data.getIv(), data.getSignature());
        log.info("WechatController.authEncrypted.[data] result=" + result);
        return Result.OK(result);
    }

    @ApiOperation("创建小程序码/二维码")
    @PostMapping("/mp/generateCode")
    public Result<?> generateMiniprogranQrCode(@RequestBody Map<String, Object> map) {
        String path = String.valueOf(map.get("path"));
        int width = Integer.parseInt(String.valueOf(map.getOrDefault("width", 430)));

        try {
            String qrCode = wechatApi.createMiniProgramQRCode(path, width);
            map.put("qrcode", qrCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Object lineColor = map.get("lineColor");
        LineColor color = null;
        if (lineColor != null) {
            color = JSONObject.parseObject(String.valueOf(lineColor), LineColor.class);
        }
        try {
            String wxacode = wechatApi.getWxacode(path, String.valueOf(map.getOrDefault("env", MiniprogramVersion.release.getVersion())), width, Boolean.parseBoolean(String.valueOf(map.getOrDefault("autoColor", false))), color, Boolean.parseBoolean(String.valueOf(map.getOrDefault("hyaline", false))));
            map.put("wxacode", wxacode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.OK(map);
    }

    //endregion================================  小程序相关接口 结束  ================================

    //region================================  公众号相关接口 开始  ================================

    @ApiOperation(value = "公众号登录凭证校验", response = OfficialAccountLoginResponse.class)
    @PostMapping("oa/patient/login")
    public Result<?> officialAccountsLogin(@RequestBody @Validated WxOfficialAccountsLoginRequest request) {
        String jsCode = request.getJsCode();
        log.info("WechatController.officialAccountsLogin.[request] code ={}", jsCode);
        OfficialAccountAccessToken token = wechatApi.getOfficialAccountAuthorizeAccessToken(jsCode);
        String accessToken = token.getAccess_token();
        String openid = token.getOpenid();
        // 设置5分钟有效
        if (StrUtil.isBlank(openid) || StrUtil.isBlank(accessToken)) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        // 获取用户信息
        WechatOfficialAccountUserInfo userInfo = wechatApi.getUserInfo(accessToken, openid);
        if (userInfo == null) {
            return error(ResponseState.STATE_OPERATION_FAILURE);
        }
        String unionid = userInfo.getUnionid();
        if (StrUtil.isBlank(unionid)) {
            // unionid 为 null 则表示没关注公众号
            return error(SystemState.ResponseState.STATE_NO_SUBSCRIBE);
        }
        // 设置返回消息
        OfficialAccountLoginResponse response = new OfficialAccountLoginResponse();
        Integer identity = null, userId = null, tagId = null;
        DtrdEntRdPatient patient = patientService.getPatientInfoByUnionId(unionid);
        log.info("WechatController.officialAccountsLogin.[request] patient=" + patient);
        DtrdEntRdDoctor doctor = doctorService.getDoctorByUnionidOrOaOpenid(unionid, null);
        log.info("WechatController.officialAccountsLogin.[request] doctor=" + doctor);
        Constant.LoginIdentity loginIdentity = Constant.LoginIdentity.valueOf(request.getIdentity());
        switch (loginIdentity) {
            case PATIENT:
                if (doctor != null) {
                    // 已经是医生 不允许再注册为患者
                    log.info("WechatController.officialAccountsLogin.[request] 已经是医生 不允许再注册为患者");
                    return error(ResponseState.STATE_OPERATION_FAILURE);
                }
                if (patient == null) {
                    patient = patientService.createPatientByOaOpenIdAndUnionid(openid, unionid);
                }
                userId = patient.getDataId();
                log.info("获取患者id: {}", patient.getDataId());
                patientService.updatePatientInfoByWechatUserInfo(userInfo, userId);
                response.setHasPhoneNumber(StrUtil.isNotBlank(patient.getPatientsMobile()));
                identity = Constant.LoginIdentity.PATIENT.getType();
                // 绑定用户标签
                tagId = WechatConstant.OfficialAccountTag.USER_TAG_ID.getTag();
                log.info("绑定客户标签: openid: {}, tagid: {}", openid, tagId);
                break;
            case DOCTOR:
                if (patient != null) {
                    // 已经是患者 不允许再注册为医生
                    log.info("WechatController.officialAccountsLogin.[request] 已经是患者 不允许再注册为医生");
                    return error(ResponseState.STATE_OPERATION_FAILURE);
                }
                if (doctor == null) {
                    doctor = doctorService.createDoctorByOaOpenidAndUnionid(openid, unionid);
                }
                userId = doctor.getDataId();
                if (StrUtil.isNotBlank(doctor.getDoctorsMobile())) {
                    response.setHasPhoneNumber(true);
                }
                log.info("获取医生id: {}", doctor.getDataId());
                doctorService.updateDoctorInfoByWechatUserInfo(userInfo, userId);
                identity = Constant.LoginIdentity.DOCTOR.getType();
                // 绑定医生标签
                tagId = WechatConstant.OfficialAccountTag.DOCTOR_TAG_ID.getTag();
                log.info("绑定医生标签, openid: {}, tagid: {}", openid, tagId);
                break;
            default:
                break;
        }
        response.setIdentity(identity);
        response.setUserId(userId);
        wechatApi.bindingTag(tagId, WechatConstant.OfficialAccountTag.getMutexTagIdList(tagId), openid);
        log.info("[WechatController.officialAccountsLogin]，登陆返回结果: {}", response);
        return Result.OK(response);
    }

    @ApiOperation(value = "绑定手机号码")
    @PostMapping("/bindmobile")
    public Result<?> bindMobileToPatient(@RequestBody WechatMobile request) {
        if (CheckUtil.isEmpty(request.getMobile())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        if (CheckUtil.isEmpty(request.getPatientId())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        log.info("绑定手机号码: {}, 用户id: {}, openid: {}", request.getMobile(), request.getPatientId(), request.getOpenId());
        Integer patientId = patientService.bindMobileToPatient(request.getPatientId(), request.getMobile());
        return patientId == null ? error(SystemState.ResponseState.STATE_PARAMS_ERROR) : Result.OK(patientId);
    }

    @ApiOperation(value = "手动绑定绑定手机号码")
    @PostMapping("/bindmobile/manual")
    public Result<?> bindMobileToPatientWithSms(@RequestBody WechatMobileManual request) {
        if (CheckUtil.isEmpty(request.getMobile())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        if (CheckUtil.isEmpty(request.getPatientId())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        String smscode = request.getCaptcha();
        Object code = redisUtil.get(request.getMobile());
        if (!smscode.equals(code)) {
            return Result.error("手机验证码错误");
        }
        Integer patientId = patientService.bindMobileToPatient(request.getPatientId(), request.getMobile());
        log.info("WechatController.bindMobileToPatientWithSms.[request = {}", request);
        return patientId == null ? error(SystemState.ResponseState.STATE_PARAMS_ERROR) : Result.OK(patientId);
    }

    @GetMapping("/signature")
    public Object signatureGetRequest(@RequestParam String signature, @RequestParam String timestamp, @RequestParam String nonce, @RequestParam String echostr) {
        log.info("WechatController.signatureGetRequest.[signature = " + signature + ", timestamp= " + timestamp + ", nonce= " + nonce + ", echostr =" + echostr);
        boolean result = wechatApi.checkSignature(signature, timestamp, nonce, WechatUtil.getNiTangConfig().getToken());
        log.info("WechatController.signatureGetRequest.[signature, timestamp, nonce, echostr] 校验结果 result = " + result);
        return result ? echostr : error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
    }

    @ApiOperation("获取微信公众号或者小程序AccessToken")
    @PostMapping("/getNiTangAccessToken")
    public Result<?> getNiTangAccessToken() {
        AccessToken accessToken = wechatApi.getAccessToken(WechatUtil.getNiTangConfig().getAppId(), WechatUtil.getNiTangConfig().getAppSecret());
        if (accessToken == null) {
            return error(SystemState.ResponseState.STATE_REQUEST_FAILURE);
        }
        return Result.OK(accessToken);
    }

    private static final String JSAPITICKET = "JSAPITICKET";

    /**
     * 获取api ticket
     */
    public String getApiTicket() {
        Object apiTicketObj = redisUtil.get(WechatUtil.getNiTangConfig().getAppId() + JSAPITICKET);
        String apiTicketStr = null;
        if (apiTicketObj == null) {
            AccessToken accessToken = wechatApi.getAccessToken(WechatUtil.getNiTangConfig().getAppId(), WechatUtil.getNiTangConfig().getAppSecret());
            if (accessToken == null) {
                log.info("WechatController.getApiTicket.[] request AccessToken 失败 ");
            } else {
                ApiTicket ticket = wechatApi.getApiTicket(accessToken.getAccessToken());
                redisUtil.set(WechatUtil.getNiTangConfig().getAppId() + JSAPITICKET, ticket.getTicket(), ticket.getExpires_in());
                apiTicketStr = ticket.getTicket();
            }
        } else {
            apiTicketStr = String.valueOf(apiTicketObj);
        }
        return apiTicketStr;
    }

    @ApiOperation(value = "微信签名", response = WechatSignature.class)
    @PostMapping("/signature")
    public Result<?> getWechatSignature(@RequestBody WechatSignatureRequest request) {
        log.info("WechatController.getWechatSignature.[request = " + request);
        if (CheckUtil.isEmpty(request.getPageUrl())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        String apiTicket = getApiTicket();
        if (apiTicket == null) {
            return error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
        }
        String noncestr = RandomStringUtils.random(10, true, true);
        long timestamp = System.currentTimeMillis();
        String signature = wechatApi.doWechatSign(apiTicket, request.getPageUrl(), noncestr, timestamp);
        WechatSignature record = new WechatSignature(noncestr, timestamp, WechatUtil.getNiTangConfig().getAppId(), signature);
        return Result.OK(record);
    }

    @ApiOperation("微信消息回调")
    @PostMapping("/msgcallback")
    public String onWechatMsgCallback(HttpServletRequest request, HttpServletResponse response) {
        String paramsAsString = getParamsAsString(request);
        log.info("WechatController.onWechatMsgCallback.[request] params= " + paramsAsString);
        try {
            OutputStream outputStream = response.getOutputStream();
            outputStream.write("success".getBytes());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
        WxEventPushBean wxEventPushBean = JaxbUtil.converyToJavaBean(paramsAsString, WxEventPushBean.class);
        String event = wxEventPushBean.getEvent();
        log.info("WechatController.onWechatMsgCallback.[request, response] event = {} wxEventPushBean = {}  ", event, wxEventPushBean);
        Constant.WxEvent wxEvent = Constant.WxEvent.typeOf(event);
        if (wxEvent != null) {
            // 根据不同事件类型执行不同操作
            switch (wxEvent) {
                case SUBSCRIBE:
                    String subscribeRes = doctorService.handleQRCodeEvent(wxEventPushBean);
                    if (StrUtil.isBlank(subscribeRes)) {
                        String s = "欢迎关注毅瑭科技！\n" + "如果您是医生，请登录或注册您的工作室账号，以便您可以对您的患者进行更好的管理。<a href=\"" + PathUtil.getH5Domain() + "/router.html?page-router=doctor\">点击这里登录或注册</a>\n\n" + "如果您是患者，请注册并完善您的信息资料，让医生更好地为您提供个性化控糖指导。<a href=\"" + PathUtil.getH5Domain() + "/router.html?page-router=patient\">点击这里注册</a>\n";
                        WxPassiveResp resp = new WxPassiveResp(wxEventPushBean);
                        subscribeRes = JaxbUtil.converTomXml(resp.buildText(WechatConstant.MsgType.text, s));
                    }
                    return subscribeRes;
                case UNSUBSCRIBE:
                    log.info("WechatController.onWechatMsgCallback.[request, response] 取消关注");
                    break;
                case SCAN:
                    String scanRes = doctorService.handleQRCodeEvent(wxEventPushBean);
                    log.info("WechatController.onWechatMsgCallback.[request, SCAN]: {}", scanRes);
                    return scanRes;
                default:
                    break;
            }
        }
        return "";
    }

    @ApiOperation("微信消息回调验证")
    @GetMapping("/msgcallback")
    public String onWechatMsgCallback(@RequestParam String signature, @RequestParam String timestamp, @RequestParam String nonce, @RequestParam String echostr) {
        boolean result = wechatApi.checkSignature(signature, timestamp, nonce, WechatUtil.getNiTangConfig().getToken());
        return result ? echostr : "failure";
    }

    @ApiOperation("发送模板测试")
    @PostMapping("/template/send")
    public Result<?> sendTemplate(@RequestBody Map map) {
        AccessToken accessToken = wechatApi.getAccessToken(WechatUtil.getNiTangConfig().getAppId(), WechatUtil.getNiTangConfig().getAppSecret());
        if (accessToken == null) {
            log.info("WechatController.sendTemplate.[map] request AccessToken 失败 ");
        } else {
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("touser", "ok2z06LcIUzLMaNM2I-kgbFlhRvA");
            paramsMap.put("template_id", "BGMMmJZkPwG8iym-lV_pawE6Qv7dVaPfVb1Oo4ms7t4");
            Integer type = StringUtil.StrTrimInt(map.get("type"));
            Integer action = StringUtil.StrTrimInt(map.get("action"));
            if (action == -1) {
                if (type == -1) {
                    paramsMap.put("url", "http://h5.test.dtx-tech.com/patient/index.html?userid=323");
                } else {
                    Map<String, String> miniProgram = new HashMap<>();
                    miniProgram.put("appid", WechatUtil.getClientId());
                    String pagepath = null;
                    String[] paths = new String[]{"pages/index/index", "pages/scan/scan", "pages/checkin/checkin", "pages/my/my", "pages/achieve/achieve", "pages/checkinRecordsDetail/checkinRecordsDetail", "pages/authorize/authorize", "pages/checkinTips/checkinTips", "pages/userInfo/userInfo", "pages/tnbInfo/tnbInfo", "pages/bindphone/bindphone", "pages/logs/logs"};
                    if (type >= 0 && type < paths.length) {
                        pagepath = paths[type];
                    }
                    if (pagepath != null) {
                        miniProgram.put("pagepath", pagepath);
                    }
                    paramsMap.put("miniprogram", JSONUtil.toJsonStr(miniProgram));
                }
                wechatApi.sendTemplateMsg(accessToken.getAccessToken(), paramsMap);
            } else {
                Integer doctorId = StringUtil.StrTrimInt(map.get("doctorId"));
                String doctorName = "熊医生";
                String doctorOpenId = StringUtil.StrTrim(map.get("doctorOpenId"));
                Integer patientId = StringUtil.StrTrimInt(map.get("patientId"));
                String patientName = StringUtil.StrTrim(map.get("patientName"));
                String patientOpenId = StringUtil.StrTrim(map.get("patientOpenId"));
                String msg = StringUtil.StrTrim(map.get("msg"));
                switch (action) {
                    case 1:
                        //
                        wechatApi.sendPatientRegisterMsg(patientName, DateUtils.formatDateTime(), msg, PathUtil.getChatroomUrl("doctor", "" + doctorId, ""), doctorOpenId);
                        break;
                    case 2:
                        wechatApi.sendPaySuccessMsg("患者支付成功：您的患者曾兰芳成功支付1888元", "购买血糖仪", DateUtils.formatDateTime(), "1888", msg, null, doctorOpenId);
                        wechatApi.sendPaySuccessMsg("患者支付成功：您的患者曾兰芳成功支付1888元", "购买服务", DateUtils.formatDateTime(), "1888", msg, PathUtil.getH5Domain() + "/patient/hMService/service.html?userid=629&packageid=1089&from=weapp&t=411", doctorOpenId);
                        break;
                    case 3:
                        wechatApi.sendAccountAuditMsg("审核通过：恭喜您成功通过认证审核！", "王医生", null, "18701242109", null, null, "点击这里进入您的个人工作室，开启您的专属控糖之旅。", PathUtil.getH5Domain() + "/doctor/doctorStudio.html?did=" + doctorId, doctorOpenId);
                        break;
                    case 4:
                        wechatApi.sendAccountAuditMsg("审核不通过：您的认证审核未能通过", "王医生", null, "18701242109", null, null, "信息不符认证失败", null, doctorOpenId);
                        break;
                    case 5:
                        wechatApi.sendBindSuccessMsg("您的患者张三绑定血糖仪成功", "", DateUtils.formatDateTime(), doctorOpenId);
                        wechatApi.sendBindSuccessMsg("您的患者张三绑定血糖仪成功", "1234567", DateUtils.formatDateTime(), doctorOpenId);
                        break;
                    case 6:
                        wechatApi.sendPaySuccessMsg("您已成功支付1888元", "购买血糖仪", DateUtils.formatDateTime(), "1888", msg, null, patientOpenId);
                        wechatApi.sendPaySuccessMsg("您已成功支付1888元", "购买服务", DateUtils.formatDateTime(), "1888", msg, PathUtil.getH5Domain() + "/patient/hMService/service.html?userid=629&packageid=1089&from=weapp&t=411", patientOpenId);
                        break;
                    default:
                        break;
                }
            }
        }
        return Result.OK();
    }

    @GetMapping("rid")
    public Result<?> getRidInfo(@RequestBody WechatRidRequest request) {
        String info = wechatApi.getRidInfo(request);
        return Result.OK(info);
    }

    @ApiOperation("保存标签")
    @PostMapping("tag/add")
    public Result<?> saveWxTag(@RequestBody CreateTagRequest request) {
        String name = request.getName();
        if (StrUtil.isBlank(name)) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        WechatCreateTagJSON json = wechatApi.createWechatTag(name);
        return Result.OK(json);
    }

    @ApiOperation("获取所有标签")
    @GetMapping("tags")
    public Result<?> getAllTags() {
        WxTagListResponse tags = wechatApi.listWechatTag();
        return Result.OK(tags);
    }

    @ApiOperation("绑定标签")
    @PostMapping("tag/binding")
    public Result<?> bindingTag(@RequestBody WxBindingTagRequest request) {
        Integer tagid = request.getTagid();
        List<String> openidList = request.getOpenid_list();
        if (CollectionUtil.isEmpty(openidList) || tagid == null) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        WechatResponse response = wechatApi.bindingTag(openidList, tagid, WechatConstant.OfficialAccountTag.getMutexTagIdList(tagid));
        return Result.OK(response);
    }

    @ApiOperation("删除用户标签")
    @PostMapping("/tag/remove")
    public Result<?> removeUserTag(@RequestBody WxBindingTagRequest request) {
        log.info("WechatController.getApi.[request] " + request);
        return Result.OK();
    }

    @ApiOperation("查询用户标签")
    @PostMapping("/tag/usertag")
    public Result<?> getUserTag(@RequestBody WxBindingTagRequest request) {
        return Result.OK();
    }

    //endregion================================  公众号相关接口 结束  ================================
}
